package com.jarvis.hospital.prescription;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.ImageActivity;
import com.jarvis.hospital.ImageDetailActivity;
import com.jarvis.hospital.R;
import com.jarvis.hospital.common.BaseFragment;
import com.jarvis.hospital.common.FileResponseData;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.model.FileModel;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.prescription.adapter.AllPrescriptionAdapter;
import com.jarvis.hospital.prescription.adapter.BloodAdapter;
import com.jarvis.hospital.prescription.model.AllBloodModel;
import com.jarvis.hospital.prescription.model.AllPrescriptionModel;
import com.jarvis.hospital.prescription.model.BloodDetailModel;
import com.jarvis.hospital.prescription.model.PrescriptionDetailModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.AddressManager;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by jarvis.liu on 2016-11-02.
 */

public class BloodFragment extends BaseFragment {
    private ApiService service;
    @BindView(R.id.recy_blood)
    RecyclerView recy_blood;
    @BindView(R.id.ptr_blood)
    PtrClassicFrameLayout ptr_blood;
    private BloodAdapter bloodAdapter;
    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;

    private int type;

    private String photo_path;
    private TextView tv_add;
    private ImageView img_pic;
    private FileModel fileModel;
    AlertDialog alertDialog;
    private  String bloodId;

    public static BloodFragment newInstance(int type) {
        Bundle args = new Bundle();
        BloodFragment fragment = new BloodFragment();
        fragment.setArguments(args);
        fragment.type = type;
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_blood;
    }

    @Override
    public void initData() {
        ptr_blood.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_blood.autoRefresh();
                    }
                }, 100);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setStatus(true);
        }

    }

    @Override
    protected void initView() {
        service = RequestApi.create(ApiService.class);
        setStatus(true);
        setAdapter();
        setRefresh();
        recy_blood.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                BloodDetailModel bloodDetailModel = bloodAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.img_analysis:
                        Bundle bundle=new Bundle();
                        bundle.putString("url",bloodDetailModel.getAnalysisPic());
                        startActivity(ImageDetailActivity.class,bundle);
                        break;
                }
            }

            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                BloodDetailModel bloodDetailModel = bloodAdapter.getData().get(i);
                UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
                String userRole = userModel.getUserRole();
                if("docimaster".equals(userRole)){
                    if (type==1) {
                        bloodId=bloodDetailModel.getBloodId();
                        showDialog();
                    }
                }


            }
        });
    }

    public void showDialog() {
        fileModel=null;
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View customView = inflater.inflate(R.layout.dia_blood, null);
        tv_add = customView.findViewById(R.id.tv_add);
        img_pic = customView.findViewById(R.id.img_pic);
        final EditText ed_value = customView.findViewById(R.id.ed_value);
        final RelativeLayout rel_yes = customView.findViewById(R.id.rel_yes);
        rel_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fileModel==null){
                    showTextToast("请上传化验单");
                }else {
                    updateBloodCheckResult(ed_value.getText().toString());
                }
            }
        });
        img_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new RxPermissions(getActivity()).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    //所有权限都开启aBoolean才为true，否则为false
                                    PhotoPicker.builder()
                                            .setPhotoCount(1)
                                            .setShowCamera(true)
                                            .setShowGif(true)
                                            .setPreviewEnabled(false)
                                            .start(getActivity(), 1);
                                } else {
                                    showTextToast("请选择允许使用权限");
                                }
                            }
                        });
            }
        });
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new RxPermissions(getActivity()).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    //所有权限都开启aBoolean才为true，否则为false
                                    PhotoPicker.builder()
                                            .setPhotoCount(1)
                                            .setShowCamera(true)
                                            .setShowGif(true)
                                            .setPreviewEnabled(false)
                                            .start(getActivity(), 1);
                                } else {
                                    showTextToast("请选择允许使用权限");
                                }
                            }
                        });
            }
        });
        AlertDialog.Builder dialogBuilder_shop = new AlertDialog.Builder(getActivity())
                .setTitle("化验结果描述")
                .setView(customView);
        alertDialog = dialogBuilder_shop.create();
        alertDialog.show();
    }
    private void updateBloodCheckResult(String value){
        showDialog("加载中");
        String path="";
        if(fileModel!=null){
            path=fileModel.getFilePath();
        }
        service.updateBloodCheckResult(bloodId,path,value)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData allPrescriptionModelResponseData) {
                        alertDialog.dismiss();
                        if (allPrescriptionModelResponseData != null) {
                            int resultCode = allPrescriptionModelResponseData.getResultCode();
                            showTextToast(allPrescriptionModelResponseData.getMessage());
                            if (resultCode == 200) {
                                ptr_blood.postDelayed(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                ptr_blood.autoRefresh();
                                            }
                                        }, 100);
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        alertDialog.dismiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                        alertDialog.dismiss();
                    }
                });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            if (data != null) {
                final ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photo_path = photos.get(0);
                upImage();
            }
        }
    }
    private void upImage() {
        showDialog("loading");
        final String url = AddressManager.getFileHost();
        ApiService service_phone = RequestApi.create(ApiService.class, url);
        File file = new File(photo_path);//filePath 图片地址
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//表单类型
                .addFormDataPart("folderName", "changzheng");//ParamKey.TOKEN 自定义参数key常量类，即参数名
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("files", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

        List<MultipartBody.Part> parts = builder.build().parts();

        Call<FileResponseData<List<FileModel>>> call = service_phone.uploadImage(parts);
        call.enqueue(new Callback<FileResponseData<List<FileModel>>>() {
            @Override
            public void onResponse(Call<FileResponseData<List<FileModel>>> call, Response<FileResponseData<List<FileModel>>> response) {
                disMiss();
                if (response.body() != null) {
                    int statusCode = response.body().getCode();
                    if (statusCode == 200) {
                        Glide.with(getActivity())
                                .load(photo_path)
                                .centerCrop()
                                .into(img_pic);
                        fileModel=response.body().getResult().get(0);
                        img_pic.setVisibility(View.VISIBLE);
                        tv_add.setVisibility(View.GONE);
                    } else {
                        showTextToast(response.body().getDesc());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<FileResponseData<List<FileModel>>> call, Throwable t) {
                disMiss();
                showTextToast(RequestApi.detailError(t));
            }
        });
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_blood.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_blood.disableWhenHorizontalMove(true);
        ptr_blood.setLastUpdateTimeRelateObject(this);
        ptr_blood.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_blood, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_blood, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadData();
                } else {
                    ptr_blood.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                bloodAdapter.setNewData(new ArrayList<BloodDetailModel>());
                currentPage = 1;
                loadData();
            }
        });
    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        bloodAdapter = new BloodAdapter(R.layout.item_blood, new ArrayList<BloodDetailModel>(), type);
        recy_blood.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_blood.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        bloodAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_blood.setAdapter(bloodAdapter);
    }

    private void loadData() {
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        service.getBloodDoneList(currentPage, pageSize, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<AllBloodModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<AllBloodModel> allBloodModelResponseData) {
                        if (allBloodModelResponseData != null) {
                            int resultCode = allBloodModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                int total_count = allBloodModelResponseData.getTotalcount();
                                maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                                bloodAdapter.addData(allBloodModelResponseData.getData().getBloodDoneList());
                            } else {
                                showTextToast(allBloodModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ptr_blood.refreshComplete();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        ptr_blood.refreshComplete();
                    }
                });
    }
}
